package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.constants.admin.AdminConstants;
import com.heima.common.exception.CustException;
import com.heima.common.exception.CustomException;
import com.heima.feigns.ArticleFeign;
import com.heima.feigns.WemediaFeign;
import com.heima.model.article.pojos.ApAuthor;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.AuthDTO;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.user.pojos.ApUserRealname;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.mapper.UserMapper;
import com.heima.user.service.Userservice;
import io.seata.spring.annotation.GlobalTransactional;
import org.apache.commons.lang3.StringUtils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


import java.util.Date;

@Service
public class UserserviceImpl extends ServiceImpl<UserMapper, ApUserRealname> implements Userservice {
    @Autowired
    ApUserMapper apUser;
    /**
     * 4.2 创建作者信息
     *
     * @param apUser
     * @param wmUser
     * @return
     */
    @Autowired
    ArticleFeign articleFeign;
    @Autowired
    WemediaFeign wemediaFeign;

    @Override
    public ResponseResult getlist(AuthDTO authDTO) {
        if (authDTO == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        authDTO.checkParam();
        LambdaQueryWrapper<ApUserRealname> wrapper = Wrappers.lambdaQuery();

        Page<ApUserRealname> objectPage = new Page<>(authDTO.getPage(), authDTO.getSize());
        if (authDTO.getStatus() != null) {
            wrapper.eq(ApUserRealname::getStatus, authDTO.getStatus());
        }

        IPage<ApUserRealname> page = this.page(objectPage, wrapper);

        return new PageResponseResult(authDTO.getPage(), authDTO.getSize(),
                page.getTotal(), page.getRecords());

    }

    @Override
    @GlobalTransactional(rollbackFor = Exception.class)
    public ResponseResult updateStatusById(AuthDTO dto, Short status) {
        //1 参数检查
        if (dto.getId() == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_REQUIRE, "id不存在");
        }
        //2 查询当前认证用户是否在 APP端有当前用户
        ApUserRealname byId = getById(dto.getId());
        if (byId == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_REQUIRE, "当前实名认证消息不存在");
        }
        if (!AdminConstants.WAIT_AUTH.equals(byId.getStatus())) {

            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW, "当前数据不是待审核");
        }

        ApUser apUser = this.apUser.selectById(byId.getUserId());
        if (apUser == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "关连的AP数据不存在");
        }

        //3 更新认证用户信息
        byId.setStatus(status);
        if (StringUtils.isNotBlank(dto.getMsg())) {
            byId.setReason(dto.getMsg());
        }
        updateById(byId);
        //4 认证状态如果为 通过
        if (!status.equals(AdminConstants.PASS_AUTH)) {
            return ResponseResult.okResult();
        }
        //4.1 创建自媒体账户
        WmUser wmUser = createWmUser(apUser);

        //4.2 创建作者信息
        createApAuthor(apUser, wmUser);

        if (dto.getId() == 5) {
            CustException.cust(AppHttpCodeEnum.LOGIN_STATUS_ERROR);
        }
        //5 返回结果
        return ResponseResult.okResult();
    }

    private void createApAuthor(ApUser apUser, WmUser wmUser) {
        //1 检查是否成功调用
        ResponseResult<ApAuthor> byUserId = articleFeign.findByUserId(apUser.getId());
        if (!byUserId.checkCode()) {
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR);
        }
        //2. 检查作者信息是否已经存在
        ApAuthor apAuthor = byUserId.getData();
        if (apAuthor != null) {
            CustException.cust(AppHttpCodeEnum.DATA_EXIST, "作者信息已经存在");
        }
        //3. 添加作者信息
        apAuthor = new ApAuthor();
        apAuthor.setName(wmUser.getName());
        apAuthor.setType(AdminConstants.AUTHOR_TYPE); // 自媒体人类型
        apAuthor.setUserId(apUser.getId()); // APP 用户ID
        apAuthor.setCreatedTime(new Date());
        apAuthor.setWmUserId(wmUser.getId()); // 自媒体用户ID

        ResponseResult result = articleFeign.save(apAuthor);


        //4. 结果失败，抛出异常
        if (!result.checkCode()) {
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR);
        }

        /**
         * 4.1 创建自媒体账户
         * @param dto
         * @param apUser  APP端用户
         * @return
         */}

    private WmUser createWmUser(ApUser apUser) {
        //1 查询自媒体账号是否存在（APP端用户密码和自媒体密码一致）
        ResponseResult<WmUser> wemedia = wemediaFeign.findByName(apUser.getName());
        if (!wemedia.checkCode()) {
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR);
        }
        WmUser data = wemedia.getData();

        if (data != null) {
            CustException.cust(AppHttpCodeEnum.DATA_EXIST, "自媒体用户已经存在了");
        }
        WmUser wmUser = new WmUser();
        wmUser.setApUserId(apUser.getId());  // app端用户id
        wmUser.setName(apUser.getName());
        wmUser.setPassword(apUser.getPassword()); // 密码
        wmUser.setSalt(apUser.getSalt());  // 盐
        wmUser.setImage(apUser.getImage());
        wmUser.setPhone(apUser.getPhone());
        wmUser.setStatus(AdminConstants.USER_STATUS_ALLOW.intValue());
        wmUser.setType(AdminConstants.AUTHOR_TYPE); // 个人
        wmUser.setCreatedTime(new Date());
        ResponseResult<WmUser> save = wemediaFeign.save(wmUser);
        if (!save.checkCode()) {
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR);
        }

        return save.getData();
    }
}
